﻿using Application.Common.Interfaces;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Application.Features.Users.Commands.Delete;

/// <summary>
/// 删除用户
/// </summary>
[Description(("删除"))]
[GroupDescription(("用户管理"))]
public class DeleteUserCommand : IRequest<bool>
{
    /// <summary>
    /// 删除用户的唯一标识
    /// </summary>
    [Required(ErrorMessage = "删除数据的唯一标识是必填的")]
    public List<long> UserIds { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class DeleteUserCommandHandler : IRequestHandler<DeleteUserCommand, bool>
{
    private readonly IApplicationDbContext _context;

    public DeleteUserCommandHandler(
        IApplicationDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
    {
        var usersToDetele = await _context.Users
            .Where(x=> request.UserIds.Contains(x.Id))
            .ToListAsync(cancellationToken);

        _context.Users.RemoveRange(usersToDetele);

        var userRolesToDetele = await _context.UserRoles
            .Where(x => usersToDetele.Select(s => s.Id).Contains(x.UserId))
            .ToListAsync(cancellationToken);

        if (userRolesToDetele.Any()) 
            _context.UserRoles.RemoveRange(userRolesToDetele);

        return true;
    }
}